/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kylingroup.Desktop.Plugin.FileUploader.Flat;

import com.kylingroup.Desktop.Plugin.FileUploader.Bean.UploadListItem;
import com.kylingroup.Desktop.Plugin.FileUploader.FileuploaderController;
import java.awt.Desktop;
import java.io.File;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javax.swing.SwingUtilities;

/**
 *
 * @author kylin
 */
public class FlatViewItem {
    private LocalFlatView flatview=null;
    private File file=null;
    private String currentPath=null;
    private VBox box=null;
    private ImageView img=null;
    private Label lname=null;
    private boolean isAdded=false;
    private ContextMenu popupMenu=null;
    private EventHandler<MouseEvent> direvent;
    private EventHandler<MouseEvent> fileevent;
    private UploadListItem upitem;

    public FlatViewItem(LocalFlatView flatview,String currentPath){
        this.flatview=flatview;
        this.currentPath=currentPath;
        
        direvent=new EventHandler<MouseEvent>(){
                @Override
                public void handle(MouseEvent e) {
                    if(e.getButton()==MouseButton.PRIMARY){
                        if(e.getClickCount()==2){
                            flatview.iterator(file.getAbsolutePath());
                        }
                    }else if(e.getButton()==MouseButton.SECONDARY){
                        if(isAdded){
                            popupMenu=createEditPopupmenu();
                        }else{
                            popupMenu=createNormalPopupmenu();
                        }
                        popupMenu.show(box, e.getScreenX(), e.getScreenY());   
                    }
                }
            };
        fileevent=new EventHandler<MouseEvent>(){
                @Override
                public void handle(MouseEvent e) {
                    if(e.getButton()==MouseButton.SECONDARY){
                        if(isAdded){
                            popupMenu=createEditPopupmenu();
                        }else{
                            popupMenu=createNormalPopupmenu();
                        }
                        popupMenu.show(box, e.getScreenX(), e.getScreenY());     
                    }else if(e.getButton()==MouseButton.PRIMARY){
                        if(e.getClickCount()==2){
                            preview(file.getAbsolutePath());
                        }
                    }
                }
            };
    }
    
    private void preview(String path){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                Desktop desktop=Desktop.getDesktop();
                            
                try{ 
                    desktop.open(new File(path));
                }catch (Exception e){
                    e.printStackTrace();  
                }
            }
        });
    }
    
    private void alert(String info){
        Alert alert=new Alert(Alert.AlertType.WARNING,"");
        alert.initModality(Modality.APPLICATION_MODAL);
        alert.initOwner(null);
        alert.getDialogPane().setContentText(info);
        alert.getDialogPane().setHeaderText(Alert.AlertType.WARNING.name());
        alert.showAndWait().filter(response -> response==ButtonType.OK).ifPresent(response -> System.out.println("The alert was approved"));
    }
    
    public void setFile(File file){
        this.file=file;
        box=new VBox();
        box.setAlignment(Pos.TOP_CENTER);
        box.setPrefSize(100, 40);
        img=new ImageView();
        if(file.getName().length()>5){
            lname=new Label(file.getName().substring(0,5)+"...");
        }else{
            lname=new Label(file.getName());
        }
        lname.setTooltip(new Tooltip(file.getName()));
        
        setIcon();
        bindAction();
    }
    
    public VBox getView(){
        box.getChildren().addAll(img,lname);
        return box;
    }
    
    public void setIcon(){
        if(file.isDirectory()){
            Image image=FileuploaderController.typeicons.get("folder0");
            img.setFitWidth(40);
            img.setFitHeight(40);
            img.setImage(image);          
        }else{
            String type=file.getName();
            type=type.substring(type.lastIndexOf(".")+1,type.length());
            Image image=FileuploaderController.typeicons.get(type);
            if(image==null){
                image=FileuploaderController.typeicons.get("default");
            }
            img.setFitWidth(35);
            img.setFitHeight(44);
            img.setImage(image);
        }
    }
    
    public ContextMenu createNormalPopupmenu(){
        ContextMenu popupMenu=new ContextMenu();
        MenuItem itemPreview=new MenuItem("view");
        MenuItem itemDelete=new MenuItem("delete");

        popupMenu.getItems().addAll(itemPreview,itemDelete);

        itemPreview.setOnAction(new EventHandler(){
            @Override
            public void handle(Event event) {
                if(Desktop.isDesktopSupported()){
                    String filePath=file.getAbsolutePath();
                    preview(filePath);
                }else{
                    alert("System do not support Desktop operation.");
                }
            }
        });

        itemDelete.setOnAction(new EventHandler(){
            @Override
            public void handle(Event event) {
                if(!file.isDirectory()){
                    if(file.delete()){
                        flatview.iterator(currentPath);
                    }
                }else{
                    if(file.listFiles().length==0){
                        if(file.delete()){
                            flatview.iterator(currentPath);
                        }
                    }else{
                        alert("Folder isn't empty.");
                    }
                }
            }
        });
        return popupMenu;
    }
    
    public ContextMenu createEditPopupmenu(){
        ContextMenu popupMenu=new ContextMenu();
        MenuItem itemRename=new MenuItem("rename");
        
        popupMenu.getItems().addAll(itemRename);

        itemRename.setOnAction(new EventHandler(){
            @Override
            public void handle(Event event) {
                box.getChildren().remove(lname);
                TextField txtrename=new TextField();
                box.getChildren().add(txtrename);
                box.setOnMouseClicked(null);
                txtrename.setOnAction(new EventHandler<ActionEvent>(){
                    @Override
                    public void handle(ActionEvent event){
                        upitem.getBox().setUserData(txtrename.getText());
                        lname.setText(txtrename.getText());
                        box.getChildren().remove(txtrename);
                        box.getChildren().add(lname);
                        bindAction();
                    }
                });
            }
        });
        return popupMenu;
    }
    private void bindAction(){
        if(file.isDirectory()){
            box.setOnMouseClicked(direvent);
        }else{
            box.setOnMouseClicked(fileevent);
        }
    }
    public boolean isIsAdded() {
        return isAdded;
    }

    public void setIsAdded(boolean isAdded) {
        this.isAdded = isAdded;
    }
    
    public UploadListItem getUpitem() {
        return upitem;
    }

    public void setUpitem(UploadListItem upitem) {
        this.upitem = upitem;
    }
}
